import Vue from 'vue'
import VueRouter from 'vue-router'
import IndexView from '@/views/layout/IndexView.vue'
import HomeView from '@/views/layout/components/HomeView.vue'
import CategoryVew from '@/views/layout/components/CategoryVew.vue'
import CartView from '@/views/layout/components/CartView.vue'
import UserView from '@/views/layout/components/UserView.vue'
import store from '@/store'
Vue.use(VueRouter)

const LoginView = () => import('@/views/login/LoginView.vue')
const MyOrderView = () => import('@/views/myorder/MyOrderView.vue')
const PayView = () => import('@/views/pay/PayView.vue')
const ProDeatilView = () => import('@/views/prodeatil/ProDeatilView.vue')
const SearchView = () => import('@/views/search/SearchView.vue')
const SearchResult = () => import('@/views/search/SearchResult.vue')

const routes = [
  {
    path: '/',
    name: 'index',
    component: IndexView,
    redirect: '/home',
    children: [
      { path: 'home', name: 'home', component: HomeView },
      { path: 'category', name: 'category', component: CategoryVew },
      { path: 'cart', name: 'cart', component: CartView },
      { path: 'user', name: 'user', component: UserView }
    ]
  },
  { path: '/login', name: 'login', component: LoginView },
  { path: '/myorder', name: 'myorder', component: MyOrderView },
  { path: '/pay', name: 'pay', component: PayView },
  { path: '/prodetail/:goodsId?', name: 'prodetail', component: ProDeatilView },
  { path: '/search', name: 'search', component: SearchView },
  { path: '/searchResult', name: 'searchResult', component: SearchResult }

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 权限页面数组
const authUrls = ['/pay', '/myOrder', 'user']
router.beforeEach((to, from, next) => {
  // 访问非权限页面，则直接next
  if (!authUrls.includes(to.path)) {
    next()
    return
  }
  const token = store.getters['user/getToken']
  // 若已登录，则next
  if (token !== '') {
    next()
    // 否则跳转登录页
  } else {
    next('/login')
  }
})

export default router
